package com.huihuiyun.huihuiyun.server.controller.member.client;

import com.huihuiyun.huihuiyun.server.controller.member.client.viewobjects.HhyMemberVO;
import com.huihuiyun.huihuiyun.server.domain.HhyMember;
import com.huihuiyun.huihuiyun.server.service.HhyMemberService;
import com.huihuiyun.huihuiyun.server.viewobject.ResultVO;
import com.huihuiyun.huihuiyun.server.viewobject.ResultVOUtil;
import com.mark.util.JaxrsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

@Component
@Path(Const.context)
@Slf4j
public class MemberClientController {
    @Context
    private HttpServletResponse httpServletResponse;

    @Autowired
    private HhyMemberService memberService;

    /*******************
     * member
     ******************/
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/member/register")
    public ResultVO<HhyMemberVO> memberRegister(HhyMemberVO hhyMemberVO) {
        try {
            String phone = hhyMemberVO.phone;
            if (memberService.findHhyMemberByPhone(phone) != null) {
                return ResultVOUtil.error("注册失败, 手机号码必须唯一");
            }
            HhyMember hhyMember = ResultVOUtil.convert(hhyMemberVO, HhyMember.class);
            hhyMember = memberService.post(hhyMember);
            hhyMemberVO = ResultVOUtil.convert(hhyMember, HhyMemberVO.class);
            return ResultVOUtil.success(hhyMemberVO);
        } catch (Exception e) {
            log.error("", e);
            return ResultVOUtil.error("注册失败");
        }
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/member/login")
    public ResultVO<HhyMemberVO> memberLogin(HhyMemberVO hhyMemberVO) {
        try {
            String phone = hhyMemberVO.phone;
            String password = hhyMemberVO.password;
            HhyMember hhyMember = memberService.findHhyMemberByPhoneAndPassword(phone, password);
            hhyMemberVO = new HhyMemberVO();
            BeanUtils.copyProperties(hhyMember, hhyMemberVO);
            return ResultVOUtil.success(hhyMemberVO);
        } catch (JaxrsUtil.JaxrsRuntimeException e) {
            log.error("", e);
            return ResultVOUtil.error("登录失败，请稍后重试");
        }
    }
}